package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.message.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ApAuthorMapper authorMapper;

    @Autowired
    private ApArticleConfigMapper articleConfigMapper;

    @Autowired
    private ApArticleContentMapper articleContentMapper;

    @Autowired
    private ApArticleMapper articleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    private String readPath;

    @Autowired
    private GeneratePageService generatePageService;

    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 100000)
    @Override
    public void publishArticle(Integer newsId) {
        //1. 根据id查询自媒体文章数据
        WmNews wmNews = getWmNews(newsId);
        //2. 封装ApArticle
        ApArticle article = getApArticle(wmNews);
        //3. 修改或保存 article信息
        saveOrUpdateArticle(article);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(wmNews, article);
        // 5. 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), article);
        // 6. 更新 wmNews状态  改为9  并设置articleId
        updateWmNewsStatus(wmNews, article);
        // 7. 通知es索引库添加文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("文章发功，并发送索引库更新通知   文章id: {}",article.getId());
    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "输入的参数为空");
        }
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        List<ApArticle> articles = articleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articles) {
            if (StringUtils.isNotBlank(article.getImages())) {
                String images = Arrays.stream(article.getImages().split(",")).map(url -> webSite + url).collect(Collectors.joining(","));
                article.setImages(images);
            }
            article.setStaticUrl(readPath + article.getStaticUrl());
        }
        return ResponseResult.okResult(articles);
    }

    @Override
    public ResponseResult loadFromCache(Short loadtype, ArticleHomeDTO dto) {
        // 去redis中查询
        String jsonStr = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if (StringUtils.isBlank(jsonStr)) {
            // 加载数据库数据
            return load(loadtype, dto);
        }
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
        List<ApArticle> apArticleList = hotArticleVoList.stream()
                .map(hotArticleVo -> {
                    ApArticle article = new ApArticle();
                    BeanUtils.copyProperties(hotArticleVo, article);
                    // 封面在前端不显示，需要我们拼接路径前缀
                    String images = article.getImages();
                    // 判断封面是否为空
                    if (StringUtils.isNotBlank(images)){
                        images = Arrays.stream(images.split(","))
                                .map(url -> webSite + url)
                                .collect(Collectors.joining(","));
                        article.setImages(images);
                        // 静态页 static_url拼接 访问前缀
                        article.setStaticUrl(readPath + article.getStaticUrl());
                    }
                    return article;
                })
                .collect(Collectors.toList());
        return ResponseResult.okResult(apArticleList);
    }

    /**
     * 更新 wmNews状态  改为9  并设置articleId
     *
     * @param wmNews
     * @param article
     */
    private void updateWmNewsStatus(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用更新 wmNews接口失败  文章id: {}", wmNews.getId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用修改文章接口失败");
        }
    }


    /**
     * 保存关联配置和内容信息
     *
     * @param wmNews
     * @param article
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle article) {
        ApArticleConfig articleConfig = new ApArticleConfig();
        articleConfig.setArticleId(article.getId());
        articleConfig.setIsComment(true);
        articleConfig.setIsForward(true);
        articleConfig.setIsDown(false);
        articleConfig.setIsDelete(false);
        articleConfigMapper.insert(articleConfig);
        ApArticleContent articleContent = new ApArticleContent();
        articleContent.setArticleId(article.getId());
        articleContent.setContent(wmNews.getContent());
        articleContentMapper.insert(articleContent);
    }

    /**
     * 修改或保存 article信息
     *
     * @param article
     */
    private void saveOrUpdateArticle(ApArticle article) {
        if (article.getId() == null) {
            //article.setCreatedTime(new Date());
            article.setCollection(0); // 收藏数
            article.setLikes(0);// 点赞数
            article.setComment(0);// 评论数
            article.setViews(0); // 阅读数
            save(article);
            return;
        }
        ApArticle apArticle = getById(article.getId());
        if (apArticle == null) {
            log.info("文章发布失败 关联的article信息不存在，article id:{}", article.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
        }
        updateById(article);
        articleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, article.getId()));
        articleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));

    }

    /**
     * 封装ApArticle
     *
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews, article);
        article.setId(wmNews.getArticleId());
        article.setLayout(wmNews.getType());
        article.setFlag((byte) 0);
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            log.error("文章发布失败 远程调用查询频道接口失败  文章id: {},频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用查询频道接口失败");
        }
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("文章发布失败 未获取到频道接口信息  文章id: {},频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "频道信息不存在");
        }
        article.setChannelName(channel.getName());
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (author == null) {
            log.error("文章发布失败 未获取到作家信息  文章id: {}, 用户id : {}", wmNews.getId(), wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作家信息不存在");
        }
        article.setAuthorId(Long.valueOf(author.getId()));
        article.setAuthorName(author.getName());
        return article;
    }

    /**
     * 根据id查询自媒体文章数据
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.findWmNewsById(newsId);
        if (!wmNewsResult.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败  文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用自媒体文章接口失败");
        }
        WmNews wmNews = wmNewsResult.getData();
        if (wmNews == null) {
            log.error("文章发布失败 未获取到自媒体文章信息  文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章信息不存在");
        }
        Short status = wmNews.getStatus();
        if (!status.equals(WmNews.Status.ADMIN_SUCCESS.getCode()) && !status.equals(WmNews.Status.SUCCESS.getCode())) {
            log.error("文章发布失败 自媒体文章状态不为 4 或 8， 不予发布   文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH, "自媒体文章状态错误");
        }
        return wmNews;
    }
}